package com.aoyama.office.libreoffice.controller;

import com.aoyama.office.config.MinioConfig;
import com.aoyama.office.utils.MinioUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/fileload")
public class FileLoadController {

    @Resource
    MinioUtils minioUtils;

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;
    /**
     * @param
     * @param response
     * @功能描述 下载文件:
     */
    @RequestMapping("/download")
    public void download(HttpServletResponse response) {
        try {
// path是指想要下载的文件的路径
            File file = new File("/Users/aoyama/logs/openoffice.pdf");
            log.info(file.getPath());
// 获取文件名
            String filename = file.getName();
// 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);

// 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

// 清空response
            response.reset();
// 设置response的Header
            response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/pdf");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }



    /**
     * @param src 想要下载的文件的路径
     * @param response
     * @功能描述 下载文件:
     */
    @RequestMapping("/remote")
    public void remote(String src, HttpServletResponse response) {
        try {

            String filename = src.substring(src.lastIndexOf("/")+1);

            // 创建URL
            URL url = new URL(src);
            // 试图连接并取得返回状态码
            URLConnection urlconn = url.openConnection();
            urlconn.connect();
            HttpURLConnection httpconn = (HttpURLConnection) urlconn;
            int httpResult = httpconn.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK) {
                InputStream fis = urlconn.getInputStream();


                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();

// 清空response
                response.reset();
// 设置response的Header
                response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
                response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
//                response.addHeader("Content-Length", "" + file.length());
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//                response.setContentType("application/pdf");
                response.setContentType("application/octet-stream");
                outputStream.write(buffer);
                outputStream.flush();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @SneakyThrows
    @PostMapping("/uploadFile")
    @ResponseBody
    public  String  uploadFile(@RequestParam("file")MultipartFile  multipartFile){
        log.info("uploadFile  ----   -----  start ");
        String imgPath = minioUtils.uploadFileSingle("demo", multipartFile);
        log.info("uploadFile  ----   -----  end {}",imgPath);
        return   imgPath;
    }

}
